import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { GoodsService } from '../../../../core/routes-services/goods.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: 'app-step3',
  templateUrl: './step3.component.html',
})
export class Step3Component implements OnInit {

  @Input() levelOptions: any [] = [];
  @Input() goodsPricesOptions: any [] = [];

  entity: any = {};
  isLoading: boolean = false;
  validateForm: FormGroup;

  constructor(private router: Router,
              private fb: FormBuilder,
              public goodsService: GoodsService,
              private message: NzMessageService) {
  }

  ngOnInit(): void {
    this.entity = this.goodsService.entity;
    // console.log("33333333")
    // console.log(this.entity)
    this.initValidateForm();
  }

  initValidateForm() {
    this.isLoading = true;
    this.validateForm = this.fb.group({});
    if (!this.entity.id || this.entity.id == 0) {// 新增
      for (const levelOption of this.levelOptions) {
        this.validateForm.addControl('price_' + levelOption.id, new FormControl(null, Validators.required));
      }
    } else {//初始化值
      for (const levelOption of this.levelOptions) {
        let goodsPrices = this.goodsPricesOptions.find((t) => t.agentLevelId == levelOption.id);
        this.validateForm.addControl('price_' + levelOption.id, new FormControl(goodsPrices?goodsPrices.price:null, Validators.required));
      }
    }
    this.isLoading = false;
  }

  submitForm(): void {
    let $this = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      //构造 渠道-价格map
      let levelPrice: any = {};
      Object.keys(this.validateForm.value).forEach((t) => {
        if (t.startsWith('price_')) {
          levelPrice[t.split('_')[1]] = $this.validateForm.value[t];
        }
      });
      if (!this.entity.id || this.entity.id == 0) {
        //新增 保存全部信息
        this.goodsService.entity.levelPrice = levelPrice;
        ++this.goodsService.step;
        this.goodsService.saveEntity(this.entity).then((res) => {
          if (res.status.toString().startsWith('20')) {
            this.message.success('保存成功');
            this.isLoading = false;
            this.initValidateForm();
            this.goBack();//gy
          } else {
            this.message.warning(res.message);
          }
          this.isLoading = false;
        }, error => {
          this.message.error(error.message ? error.message : error.error);
          this.isLoading = false;
        });
      }else {
        //修改
        if(this.validateForm.dirty){
          this.goodsService.updatePrices(this.entity.id, {'levelPrice':levelPrice}).then((res) => {
            if (res.status.toString().startsWith('20')) {
              this.message.success('保存成功');
              this.isLoading = false;
              this.initValidateForm();
              this.goBack();
            } else {
              this.message.warning(res.message);
            }
            this.isLoading = false;
          }, error => {
            this.message.error(error.message ? error.message : error.error);
            this.isLoading = false;
          });
        }else {
          this.goBack();
        }
      }
    }
  }


  prev() {
    --this.goodsService.step;
  }

  goBack() {
    this.router.navigate(['/goods/list']);
  }


}
